import { defineStore } from 'pinia'
import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi } from '@/api/auth'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null,
    permissions: [],
    roles: []
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    hasPermission: (state) => (permission) => {
      return state.permissions.includes(permission)
    },
    hasRole: (state) => (role) => {
      return state.roles.includes(role)
    }
  },

  actions: {
    // 登录
    async login(loginForm) {
      try {
        const response = await loginApi(loginForm)
        const { token } = response.data
        
        // 保存token
        this.token = token
        localStorage.setItem('token', token)
        
        // 获取用户信息
        await this.getUserInfo()
        
        return { success: true }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, message: error.message }
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await getUserInfoApi()
        console.log('获取用户信息API响应:', response)
        
        // 后端直接返回UserInfoVO，不是嵌套在userInfo字段中
        const userData = response.data
        console.log('用户数据:', userData)
        
        this.userInfo = userData
        this.permissions = userData.permissions || []
        this.roles = userData.roles || []
        
        console.log('设置的userInfo:', this.userInfo)
        console.log('设置的roles:', this.roles)
        console.log('设置的permissions:', this.permissions)
        
        return { success: true }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果获取用户信息失败，清除token
        this.logout()
        return { success: false }
      }
    },

    // 退出登录
    async logout() {
      try {
        await logoutApi()
      } catch (error) {
        console.error('退出登录失败:', error)
      } finally {
        // 清除本地数据
        this.token = ''
        this.userInfo = null
        this.permissions = []
        this.roles = []
        localStorage.removeItem('token')
        
        // 跳转到登录页
        router.push('/login')
      }
    },

    // 检查权限 - 临时返回true以测试菜单
    checkPermission(permission) {
      console.log('权限检查:', permission, '当前权限:', this.permissions)
      return true // 临时返回true，忽略所有权限检查
      // return this.permissions.includes(permission)
    },

    // 检查角色
    checkRole(role) {
      return this.roles.includes(role)
    }
  }
})
